package com.chinasoft.mall.activity;

import java.io.File;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;

import com.chinasoft.mall.R;
import com.chinasoft.mall.framework.Config;
import com.chinasoft.mall.model.BaseBean;
import com.chinasoft.mall.model.DownloadInfo;
import com.chinasoft.mall.model.response.GetStartImgBean;
import com.chinasoft.mall.model.response.UpdateBean;
import com.chinasoft.mall.service.UpdateService;
import com.chinasoft.mall.util.LocalDataCommend;
import com.chinasoft.mall.util.StringUtil;
import com.chinasoft.mall.util.SystemSetting;
import com.chinasoft.mall.widget.NetImageView;
import com.chinasoft.mall.widget.NetImageView.ImageViewCallback;

@SuppressLint("HandlerLeak")
public class LoadingActivity extends BaseActivity {

	private BaseBean get_url;
	// 获取前一天或者当天或者后一天的节目单请求
	private BaseBean get_epg;
	private BaseBean get_rechn;
	private BaseBean update;
	// 加载需要更新的首页图片
	private BaseBean getImg_bb;
	private NetImageView load_img;
	private String old_bitMapurl;
	private String old_bitMaptime;
	private File file;
	
	//第一次启动app的判断
	private static final String IS_FIRST_LOGIN = "isfrist";

	@SuppressLint("HandlerLeak")
	Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == -1) {                                                           //msg.what == -1 硬代码
				load_img.setImageBitmap((Bitmap) msg.obj);
			} else if (msg.what == -2) {                                                    //
				load_img.setImageResource(R.drawable.loadimg);
			} else if (msg.what == -3) {
				DownloadInfo dli = (DownloadInfo) msg.obj;
				LocalDataCommend.saveOriginalString(LoadingActivity.this,
						"startimg", dli.getLocalpath());
				LocalDataCommend.saveOriginalString(LoadingActivity.this,
						"starttime", dli.getTempTime());
			}
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loading);
		boolean isFirst = LocalDataCommend.getOriginalBoolean(this, IS_FIRST_LOGIN,
				true);
		initView();
		if (isFirst) {
			// delShortcut();
			createDeskShortCut();
			LocalDataCommend.saveOriginalBoolean(this, IS_FIRST_LOGIN, false);
		}

		// HTTP connection reuse which was buggy pre-froyo
		// if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO)
		// {
		// System.setProperty("http.keepAlive", "false");
		// }
	}

	private void initView() {
		//主界面背景图片
		load_img = (NetImageView) findViewById(R.id.load_img);
		old_bitMapurl = LocalDataCommend.getOriginalString(
				LoadingActivity.this, "startimg", "");
		old_bitMaptime = LocalDataCommend.getOriginalString(
				LoadingActivity.this, "starttime", "");
		if ("".equals(old_bitMapurl)) {                                                //"".equals(old_bitMapurl)硬代码
			load_img.setImageResource(R.drawable.loadimg);
		} else {
			file = new File(old_bitMapurl);
			if (file.exists()) {
				Thread t = new Thread(new Runnable() {

					@Override
					public void run() {
						// old_bitMapurl = getStartImgUrl();
						if (!"".equals(old_bitMapurl)) {
							Bitmap _bitMap = BitmapFactory
									.decodeFile(old_bitMapurl);
							Message msg = new Message();
							msg.what = -1;
							msg.obj = _bitMap;
							handler.sendMessage(msg);
						}/*
						 * else { Message msg = new Message(); msg.what = -2;
						 * handler.sendMessage(msg); }
						 */
					}
				});
				t.start();
			} else {
				load_img.setImageResource(R.drawable.loadimg);
				old_bitMapurl = null;
			}
		}
	}

	
	/**
	 * 删除程序的快捷方式
	 */
	public void delShortcut() {
		Intent intent = new Intent(
				"com.android.launcher.action.UNINSTALL_SHORTCUT");

		intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));

		ComponentName comp = new ComponentName("com.chinasoft.mall",

		"com.chinasoft.mall.activity.LoadingActivity");

		intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent()

		.setComponent(comp).setAction("android.intent.action.MAIN"));

		sendBroadcast(intent);

	}

	/**
	 * 创建快捷方式
	 */
	public void createDeskShortCut() {

		Log.i("coder", "------createShortCut--------");
		// 创建快捷方式的Intent
		Intent shortcutIntent = new Intent(
				"com.android.launcher.action.INSTALL_SHORTCUT");
		// 不允许重复创建
		shortcutIntent.putExtra("duplicate", false);
		// shortcutIntent.setAction("android.intent.action.MAIN");
		// shortcutIntent.addCategory("android.intent.category.LAUNCHER");
		// 需要现实的名称
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
				getString(R.string.app_name));

		// 快捷图片
		Parcelable icon = Intent.ShortcutIconResource.fromContext(
				getApplicationContext(), R.drawable.app_icon);

		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);

		Intent intent = new Intent(getApplicationContext(),
				LoadingActivity.class);

		// 点击快捷图片，运行的程序主入口
		shortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
		// 发送广播。OK
		sendBroadcast(shortcutIntent);
		Log.i("coder", "------createShortCut--------OK!!!!!");
	}

	private boolean checkNetWorkStatus() {
		ConnectivityManager connectivity = (ConnectivityManager) getApplicationContext()
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (connectivity != null) {
			NetworkInfo info = connectivity.getActiveNetworkInfo();
			if (info != null)
				if (info.getState() == NetworkInfo.State.CONNECTED) {
					return true;
				}
		}
		return false;
	}

	@Override
	protected void onResume() {
		super.onResume();

		if (checkNetWorkStatus()) {
			// 加载需要更新的首页图片
			if (getImg_bb == null) {
				getImg_bb = new BaseBean(Config.STARTIMG);
				control.postMessage(getImg_bb);
			}
			get_url = new BaseBean(Config.GET_URL);
			get_url.setUrl_type((byte) 1);
			control.postMessage(get_url);
//			get_epg = new BaseBean(Config.GET_EPG);
//			control.postMessage(get_epg);
			get_rechn = new BaseBean(Config.GET_RECHN);
			get_rechn.setAdd(true);
			control.postMessage(get_rechn);
			update = new BaseBean(Config.UPDATE);
			update.setUrl_type((byte) 2);
			control.postMessage(update);
		} else {
			showDialog();
		}
	}

	private void showDialog() {
		Builder dialog = new AlertDialog.Builder(this);
		dialog.setTitle("提示");
		dialog.setMessage("网络不可用，请检测网络");

		// 创建事件监听器对象
		android.content.DialogInterface.OnClickListener onClickListener = new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				switch (which) {
				case DialogInterface.BUTTON2:
					android.os.Process.killProcess(android.os.Process.myPid());
					// 系统退出
					System.exit(0);
					break;
				default:
					break;
				}
			}
		};
		dialog.setNegativeButton("退出", onClickListener);
		dialog.show();                                                 //异常
	}

	@Override
	public void success(BaseBean obj) {
		super.success(obj);
		if (obj.equals(getImg_bb)) {
			if (getImg_bb.getResData() != null) {
				@SuppressWarnings("unchecked")
				List<GetStartImgBean> gsib = (List<GetStartImgBean>) getImg_bb
						.getResData().getData();
				if (gsib != null && gsib.size() > 0) {
					GetStartImgBean sbib = gsib.get(0);
					String img_url = StringUtil.getLogo(sbib.getIMG_URL());
					final DownloadInfo dli = new DownloadInfo(img_url, null,
							false);
					dli.setTempTime(sbib.getPUB_DATE());
					if ((!dli.getLocalpath().equals(old_bitMapurl))
							|| (!old_bitMaptime.equals(sbib.getPUB_DATE()))) {
						if (file != null && file.exists()) {
							file.delete();
						}
						load_img.downloadbySize(img_url, 0, 0, false, false,
								new ImageViewCallback() {

									@Override
									public Drawable beforeDraw(Drawable drawable) {
										handler.sendMessage(handler
												.obtainMessage(-3, dli));
										return null;
									}
								});
					}
					/*
					 * if (load_img.getDownloadurl() == null) { //
					 * load_img.setDownload(StringUtil.getLogo(sbib //
					 * .getIMG_URL())); load_img.downloadbySize(img_url, 0, 0,
					 * false, false, new ImageViewCallback() {
					 * 
					 * @Override public Drawable beforeDraw(Drawable drawable) {
					 * handler.sendMessage(handler .obtainMessage(-3,
					 * dli.getLocalpath())); return drawable; } }); } else if
					 * (load_img.getDownloadurl() != StringUtil
					 * .getLogo(sbib.getIMG_URL())) { File file = new
					 * File(load_img.getDownloadurl()); file.delete();
					 * load_img.downloadbySize(img_url, 0, 0, false, false, new
					 * ImageViewCallback() {
					 * 
					 * @Override public Drawable beforeDraw(Drawable drawable) {
					 * handler.sendMessage(handler .obtainMessage(-3,
					 * dli.getLocalpath())); return drawable; } }); }
					 */
				}
			}
		} else if (obj.equals(get_url)) {
//			get_epg = new BaseBean(Config.GET_EPG);
//			control.postMessage(get_epg);
			get_rechn = new BaseBean(Config.GET_RECHN);
			get_rechn.setAdd(true);
			control.postMessage(get_rechn);
			update = new BaseBean(Config.UPDATE);
			update.setUrl_type((byte) 2);
			control.postMessage(update);
		} else if (obj.equals(get_rechn)) {
			// Intent intent = new Intent();
			// intent.setClass(this, MainActivity.class);
			// startActivity(intent);
			// this.finish();
		} else if (obj.equals(update)) {
			UpdateBean _ub = (UpdateBean) update.getResData().getData();
			if (_ub != null && _ub.getUrl() != null && !"".equals(_ub.getUrl())) {
				callUpdateDialog("1", _ub.getUrl(), null);
			} else {
				initApplication();
			}
		}
	}

	private void callUpdateDialog(String type, String url, String updateMessage) {
		final String updateUrl = url;
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		if ("2".equals(type)) {
			builder.setTitle("升级提示")
					.setMessage("您的版本过旧，需要升级才能运行程序！")
					.setPositiveButton("现在升级",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									Intent intent = new Intent();
									intent.putExtra("url", updateUrl);
									intent.setClass(LoadingActivity.this,
											UpdateService.class);
									startService(intent);
									dialog.dismiss();
									LoadingActivity.this.finish();
								}
							}).show();
		} else if ("1".equals(type)) {                                                      
			builder.setTitle("升级提示")
					.setMessage(
							updateMessage == null ? "发现新版本，是否立刻升级？"
									: updateMessage)
					.setPositiveButton("现在升级",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
									System.out
											.println("$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$1");
									dialog.dismiss();
									Intent intent = new Intent();
									intent.putExtra("url", updateUrl);
									intent.setClass(LoadingActivity.this,
											UpdateService.class);
									startService(intent);
									initApplication();
								}
							})
					.setNegativeButton("以后再说",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.dismiss();
									initApplication();
								}
							}).show();
		}

	}

	public String getStartImgUrl() {
		File file = new File(SystemSetting.getDownloadFilePath());
		String[] downloadUrls = file.list();
		if (downloadUrls != null)
			for (String downloadUrl : downloadUrls) {
				if (downloadUrl.contains("start_img")) {
					return SystemSetting.getDownloadFilePath() + downloadUrl;
				}
			}
		return null;
	}

	protected void initApplication() {                    
		Intent intent = new Intent();
		intent.setClass(this, MainActivity.class);
		startActivity(intent);
		this.finish();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			android.os.Process.killProcess(android.os.Process.myPid());
			// 系统退出
			System.exit(0);
			return true;
		} else {
			return super.onKeyDown(keyCode, event);
		}
	}
}
